//
//  WMImageComparisonViewController.swift
//  deWaterMarkingProject
//
//  Created by admin on 2025/9/11.
//

import UIKit
import Alamofire
import AVKit

class WMImageComparisonViewController: WMBaseViewController {
    
    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var beforeImageView: UIImageView!
    @IBOutlet weak var afterImageView: UIImageView!
    @IBOutlet weak var sliderLine: UIView!
    @IBOutlet weak var sliderLineLeadingConstraint: NSLayoutConstraint!
    
    var beforeImage: UIImage?
    var afterImage: UIImage?
    var temporaryImage: UIImage?
    var maskImage: UIImage?
    var cropAlertView: WMCroppingAlertView?
    private var initialSliderPosition: CGFloat = 0
    private var containerWidth: CGFloat = 0
    private var isInitialSetupDone = false // 添加标志位防止重复设置
    
    var API_KEY = "YOUR_API_KEY"
    let BASE_URL = "https://techsz.aoscdn.com/api/tasks/visual/inpaint"
    
    var player: AVPlayer?
    var playerViewController: AVPlayerViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        isNavigationBarHidden = true
        self.beforeImageView.image = beforeImage
        self.afterImageView.image = afterImage
        self.beforeImageView.contentMode = .scaleAspectFit
        self.afterImageView.contentMode = .scaleAspectFit
        self.showFrame()
        // 禁用侧滑返回手势
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    //弹框
    func showFrame() {
        let showFrame: Bool = UserDefaults.standard.value(forKey: UserDefaultsKey.fixBulletFrame) as? Bool ?? false
        
        if(showFrame == false){
            cropAlertView = (UIView.viewFromNib(nibName: "WMCroppingAlertView") as! WMCroppingAlertView)
            cropAlertView!.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
            cropAlertView?.tryBlock = { //去试试
                self.cropAlertView?.removeFromSuperview()
                let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
                if member {
                    let comparisionVC = WMEraseWatermarkManuallyViewController()
                    comparisionVC.image = self.afterImage
                    comparisionVC.popBlock = { originalImage, maskImage in
                        self.temporaryImage = originalImage;
                        self.maskImage = maskImage;
                        self.start()
                    }
                    self.navigationController?.pushViewController(comparisionVC, animated: true)
                }else {
                    self.requestPermission { [weak self] status, msg in
                        if status {
                            self?.shareOpt()
                        }else {
                            Async.main {
                                self?.hideHUD()
                                self?.showTips(msg)
                                Async.main(after: 1) {
                                    let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                                    self?.navigationController?.pushViewController(vc, animated: true)
                                }
                            }
                        }
                    }
                }
            }
            
            cropAlertView?.lookBlock = { [weak self] in //查看教程
                guard let self = self else { return }
                self.cropAlertView?.removeFromSuperview()
//                let videoVC = WMVideoPlayerViewController()
//                videoVC.videoURL = URL(string: UserDefaults.standard.value(forKey: UserDefaultsKey.videojc) as? String ?? "")
//                self.navigationController?.pushViewController(videoVC, animated: true)
                guard let videoURL = URL(string: UserDefaults.standard.value(forKey: UserDefaultsKey.videojc) as? String ?? "") else {
                    print("视频URL无效")
                    return
                }
                
                // 创建AVPlayerItem和AVPlayer
                let playerItem = AVPlayerItem(url: videoURL)
                self.player = AVPlayer(playerItem: playerItem)
                
                // 创建AVPlayerViewController并设置播放器
                self.playerViewController = AVPlayerViewController()
                self.playerViewController?.player = self.player
                
                if let playerVC = self.playerViewController {
                    self.present(playerVC, animated: true) { 
                        self.player?.play() // 开始播放视频
                    }
                }
            }
            UIApplication.shared.delegate?.window??.addSubview(cropAlertView!)
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        // 确保在布局完成后获取正确的宽度
        containerWidth = view.bounds.width
        
        // 只在首次布局时设置初始位置
        if !isInitialSetupDone && containerWidth > 0 {
            let initialPosition = containerWidth / 2
            sliderLineLeadingConstraint.constant = initialPosition
            updateAfterImageViewMask()
            isInitialSetupDone = true
        }
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 确保侧滑返回手势被禁用
//        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 离开页面时重新启用侧滑返回手势
//        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
    }
    
    
    // 更新afterImageView的遮罩
    private func updateAfterImageViewMask() {
        // 计算图片在imageView中的实际显示区域（考虑AspectFit）
               let imageViewSize = afterImageView.bounds.size
               guard let imageSize = afterImage?.size else { return }
               
               let widthRatio = imageViewSize.width / imageSize.width
               let heightRatio = imageViewSize.height / imageSize.height
               let scale = min(widthRatio, heightRatio)
               
               let scaledImageSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
               let imageFrame = CGRect(
                   x: (imageViewSize.width - scaledImageSize.width) / 2,
                   y: (imageViewSize.height - scaledImageSize.height) / 2,
                   width: scaledImageSize.width,
                   height: scaledImageSize.height
               )
               
               // 计算遮罩位置，确保与滑块位置对齐
               let sliderPosition = sliderLineLeadingConstraint.constant
               let maskX = max(imageFrame.minX, sliderPosition)
               let maskWidth = max(0, imageFrame.maxX - maskX)
               
               let maskLayer = CAShapeLayer()
               let path = UIBezierPath(rect: CGRect(x: maskX, y: imageFrame.minY,
                                                    width: maskWidth,
                                                    height: imageFrame.height))
               maskLayer.path = path.cgPath
               afterImageView.layer.mask = maskLayer
    }
    
    //返回按钮点击事件
    @IBAction func backBtnClickAction(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    //手动擦除水印
    @IBAction func eraseWatermarkManuallyBtnClickAction(_ sender: Any) {
        
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            let comparisionVC = WMEraseWatermarkManuallyViewController()
            comparisionVC.image = afterImage
            comparisionVC.popBlock = { originalImage, maskImage in
                self.temporaryImage = originalImage;
                self.maskImage = maskImage;
                self.start()
            }
            self.navigationController?.pushViewController(comparisionVC, animated: true)
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.shareOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
        

    }
    
    //分享
    @IBAction func shareBtnClickAction(_ sender: Any) {
        
        //判断会员
        if !WXApi.isWXAppInstalled() {
          return KBToast.show("暂无可分享的平台")
        }
        
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            shareOpt()
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.shareOpt()
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
        
        
    }
    
    func shareOpt() {
        let shareView = ShareView(frame: UIScreen.main.bounds)
        shareView.shareItemBlock = { index in
            if(index == 0){
                self.shareImage(to: WXSceneSession)
            }else{
                self.shareImage(to: WXSceneTimeline)
            }
            
        }
        UIApplication.shared.delegate?.window??.addSubview(shareView)
    }
    
    // 分享图片到微信会话（好友）或朋友圈
       func shareImage(to scene: WXScene) {
           // 1. 创建分享消息对象
           let message = WXMediaMessage()

           // 2. 创建图片对象
           let imageObject = WXImageObject()
           // 设置图片数据（注意：图片数据不能超过10MB）
           if let image = self.afterImage {
               // 压缩图片数据，确保大小在10MB以内
               if let imageData = image.jpegData(compressionQuality: 0.7) {
                   imageObject.imageData = imageData
               }
           }

           message.mediaObject = imageObject

           // 3. 创建发送请求对象
           let req = SendMessageToWXReq()
           req.bText = false
           req.message = message
           req.scene = Int32(scene.rawValue) // 分享到聊天界面或朋友圈

           // 4. 发送请求
           WXApi.send(req) { success in
               if success {
                   print("发送成功")
               } else {
                   print("发送失败")
               }
           }
       }
    
    //保存到相册
    @IBAction func savePhotoBtnClickAction(_ sender: Any) {
        self.saveBtn.isUserInteractionEnabled = false;
        requestEventSave(title: "点击保存", mode: "点击保存")
        // 获取当前显示的图片（这里以 afterImageView 为例）
        guard let imageToSave = afterImageView.image else {
            KBToast.show("没有可保存的图片")
            return
        }
        
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        if member {
            self.savePhoto(saveImage: imageToSave)
        }else {
            requestPermission { [weak self] status, msg in
                if status {
                    self?.savePhoto(saveImage: imageToSave)
                }else {
                    Async.main {
                        self?.hideHUD()
                        self?.showTips(msg)
                        Async.main(after: 1) {
                            self?.saveBtn.isUserInteractionEnabled = true;
                            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
                            self?.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                }
            }
        }
        
       
    }
    
    func savePhoto(saveImage: UIImage) {
        //校验权限
        checkAlbunAuthority { granted in
           
            if (granted) {
                self.showHUD()
                // 权限已授权，保存图片
                UIImageWriteToSavedPhotosAlbum(
                    saveImage,
                    self,
                    #selector(self.image(_:didFinishSavingWithError:contextInfo:)),
                    nil
                )
                requestEventSave(title: "保存到本地", mode: "保存到本地")
            }else {
                KBMerPrtmissionView.show(type: .PhotoLibrary)
                return;
            }
        }
    }
    
    @IBAction func handlePan(_ gesture: UIPanGestureRecognizer) {
        
        guard let constraint = sliderLineLeadingConstraint else { return }
        
        let translation = gesture.translation(in: view)
        
        switch gesture.state {
        case .began:
            initialSliderPosition = constraint.constant
            
        case .changed:
            var newPosition = initialSliderPosition + translation.x
            newPosition = max(0, min(newPosition, containerWidth))
            constraint.constant = newPosition
            updateAfterImageViewMask()
            
        case .ended, .cancelled:
            UIView.animate(withDuration: 0.2) {
                self.view.layoutIfNeeded()
            }
            
        default:
            break
        }
    }
    
    // 保存完成后的回调
    @objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        hideHUD()
        self.saveBtn.isUserInteractionEnabled = true;
        if let error = error {
            KBToast.show("保存失败" )
        } else {
            KBToast.show("图片已保存到相册")
        }
    }
    
    func requestPermission(_ complation: @escaping (Bool, String)->Void) {
        WMAgentApi.shared.requestApi(ApiEnum.permission) { res in
            let code: String = res["code"] as! String
            let message: String? = res["message"] as? String
            complation((code == "200" || code == "0"), message.or(""))
        }
    }
    
}

extension WMImageComparisonViewController {
    /// Begin task
    func start() {
        let member = (UserDefaults.standard.value(forKey: UserDefaultsKey.isMember) as? Int ?? 0) == 1
        let picfree = UserDefaults.standard.value(forKey: UserDefaultsKey.picfree) as? Int ?? 0
        var useCount = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzTotalUseCount) as? Int ?? 0
        if(!member && useCount >= picfree){
            let vc = WMPaymentCenterController(nibName: "WMPaymentCenterController", bundle: nil)
            navigationController?.pushViewController(vc, animated: true)
        }
        // 记录每天的解析次数
        var count = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyzUseCount) as? Int ?? 0
        let maxCount = UserDefaults.standard.value(forKey: UserDefaultsKey.picslimit) as? Int ?? 0
        if count > maxCount {
            showTips(UserDefaults.standard.value(forKey: UserDefaultsKey.picsdesc) as? String ?? "")
            return
        }
        count += 1
        useCount += 1
        UserDefaults.standard.set(count, forKey: UserDefaultsKey.picxyzUseCount)
        UserDefaults.standard.set(useCount, forKey: UserDefaultsKey.picxyzTotalUseCount)
        UserDefaults.standard.synchronize()
        
        showHUD()
        createTask { taskId in
            // Task succeed, get result. Polling requests using the following methods 1. The polling interval is                  set to 1 second, 2. The polling time does not exceed 30 seconds
            let startTime = CFAbsoluteTimeGetCurrent()
            self.getTaskResult(taskId: taskId, taskStartTime: startTime) { result in
                print(result)
                self.hideHUD()
                let imageUrl: String = result["image"] as? String ?? ""
                self.afterImageView.setImageUrl(imageUrl)
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
                    self?.afterImage = self?.afterImageView.image
                    self?.updateAfterImageViewMask() // 更新遮罩
                }
                requestEventSave(title: "去水印完成", mode: "manual")
            }
        }
    }

    /// Create a task
    func createTask(completion: @escaping (String) -> Void) {
        let url = URL(string: BASE_URL)!
        API_KEY = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyz) as? String ?? ""
        let headers: HTTPHeaders = [
            "X-API-KEY": API_KEY
        ]
        
        let imagePath = saveImageAndGetPath(image: self.temporaryImage!)
        let maskImagepath = saveImageAndGetPath(image: self.maskImage!)
        
        AF.upload(multipartFormData: { multipartFormData in
            
            // 上传第一个图片（原图）
             multipartFormData.append(URL(fileURLWithPath: imagePath!), withName: "image_file", fileName: "image.jpg", mimeType: "image/jpeg")
             
             // 上传第二个图片（遮罩图）
             multipartFormData.append(URL(fileURLWithPath: maskImagepath!), withName: "mask_file", fileName: "mask.jpg", mimeType: "image/jpeg")
             
            if let data = "0".data(using: .utf8) {
                multipartFormData.append(data, withName: "sync")
            }
            if let maskData = "0".data(using: .utf8) {
                multipartFormData.append(maskData, withName: "maskData")
            }
        }, to: url, method: .post, headers: headers).responseData { response in
            switch response.result {
            case .success(let value):
                if let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
                   let data = json["data"] as? [String: Any],
                   let taskId = data["task_id"] as? String {
                    completion(taskId)
                }
            case .failure(let error):
                self.hideHUD()
                print(error)
            }
        }
    }

    /// Get result
    func getTaskResult(taskId: String,
                       taskStartTime: CFAbsoluteTime,
                       completion: @escaping ([String: Any]) -> Void) {
        let url = URL(string: "\(BASE_URL)/\(taskId)")!
        API_KEY = UserDefaults.standard.value(forKey: UserDefaultsKey.picxyz) as? String ?? ""
        let headers: HTTPHeaders = [
            "X-API-KEY": API_KEY
        ]
        
        AF.request(url, method: .get, headers: headers).responseData { response in
            switch response.result {
                case .success(let value):
                self.hideHUD()
                    print(response.debugDescription)
                    guard let json = try? JSONSerialization.jsonObject(with: value) as? [String: Any],
                          let data = json["data"] as? [String: Any],
                          let state = data["state"] as? Int else {
                        print("parse failed")
                        return
                    }
                    // Task failed, log the details, and exit the loop
                    if state < 0 {
                        return
                    }
                    // Task successful
                    if state == 1 {
                        if let imageUrlStr = data["image"] as? String {
                            completion(["image": imageUrlStr])
                            return
                        }
                    }
                          // Retrieve the results by looping only thirty times
                    let endTime = CFAbsoluteTimeGetCurrent()
                    if endTime - taskStartTime < 30 {
                        // Wait for one second between each loop iteration
                        sleep(1)
                        self.getTaskResult(taskId: taskId, taskStartTime: taskStartTime, completion: completion)
                        return
                    }
                    // Timeout, log the details, and search for support from the picwish service
                    print("timeout")
                case .failure(let error):
                    // Request from user server failed. Please record the relevant error logs
                self.hideHUD()
                    print(error)
            }
        }
    }
    
    func saveImageAndGetPath(image: UIImage) -> String? {
        guard let data = image.pngData() else { return nil }
        
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileName = "image_\(Date().timeIntervalSince1970).png"
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        
        do {
            try data.write(to: fileURL)
            return fileURL.path
        } catch {
            print("Error saving image: \(error)")
            return nil
        }
    }
}
